<template>
    <div class="default-main">
        <div class="banner">
            <el-row :gutter="20" class="row">
                <el-col :md="24" :lg="18">
                    <div class="welcome suspension">
                        <img class="welcome-img" :src="headerSvg" alt="" />
                        <div class="welcome-text">
                            <div class="welcome-title">{{ adminInfo.nickname + t('utils.comma') + getGreet() }}</div>
                            <!-- <div class="welcome-note">{{ state.remark }}</div> -->
                        </div>
                    </div>
                </el-col>
                <el-col :lg="6" class="hidden-md-and-down">
                    <div class="working">
                        <img class="working-coffee" :src="coffeeSvg" alt="" />
                        <div class="working-text">
                            {{ t('dashboard.You have worked today') }}<span class="time">{{ state.workingTimeFormat }}</span>
                        </div>
                        <div @click="onChangeWorkState()" class="working-opt working-rest">
                            {{ state.pauseWork ? t('dashboard.Continue to work') : t('dashboard.have a bit of rest') }}
                        </div>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20" class="row">
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.yesterday.order}}</div>
                                <div class="text">昨日接单</div>
                            </div>
                            <div class="icon icon1">
                                <Icon name="el-icon-DataLine" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.yesterday.commplete}}</div>
                                <div class="text">昨日出货订单</div>
                            </div>
                            <div class="icon icon2">
                                <Icon name="el-icon-TrendCharts" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.week.order}}</div>
                                <div class="text">上周接单</div>
                            </div>
                            <div class="icon icon3">
                                <Icon name="el-icon-Coin" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.week.commplete}}</div>
                                <div class="text">上周出货订单</div>
                            </div>
                            <div class="icon icon4">
                                <Icon name="el-icon-DataAnalysis" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.month.order}}</div>
                                <div class="text">本月接单</div>
                            </div>
                            <div class="icon icon5">
                                <Icon name="el-icon-DataLine" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
                <el-col :span="4">
                    <el-card shadow="hover">
                        <div class="total-item">
                            <div class="text">
                                <div class="num">{{state.month.commplete}}</div>
                                <div class="info">本月出货订单</div>
                            </div>
                            <div class="icon icon6">
                                <Icon name="el-icon-TrendCharts" />
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
            <el-row :gutter="20"  class="row">
                <el-col :span="12">
                    <el-card>
                        <div class="chart" id="chart1"></div>
                    </el-card>
                </el-col>
                <el-col :span="12">
                    <el-card>
                        <div class="chart" id="chart2"></div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
               
    </div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, reactive, nextTick, onActivated, watch, onBeforeMount } from 'vue'
import headerSvg from '/@/assets/dashboard/header-1.svg'
import coffeeSvg from '/@/assets/dashboard/coffee.svg'
import { CountUp } from 'countup.js'
import * as echarts from 'echarts'
import { useNavTabs } from '/@/stores/navTabs'
import { useTemplateRefsList } from '@vueuse/core'
import { index } from '/@/api/backend/dashboard'
import { useI18n } from 'vue-i18n'
import { Local } from '/@/utils/storage'
import { useAdminInfo } from '/@/stores/adminInfo'
import { WORKING_TIME } from '/@/stores/constant/cacheKey'
import { fullUrl, getGreet,timeFormat } from '/@/utils/common'
import { useEventListener } from '@vueuse/core'
import { statics } from '/@/api/backend'

let workTimer: number
let chart1:any 
let chart2:any 
let option:any 

defineOptions({
    name: 'dashboard',
})

const d = new Date()
const { t } = useI18n()
const navTabs = useNavTabs()
const adminInfo = useAdminInfo()
const chartRefs = useTemplateRefsList<HTMLDivElement>()

let state: any = reactive({
    'yesterday': {'order': 0, 'commplete': 0},
    'week': {'order': 0, 'commplete': 0},
    'month': {'order': 0, 'commplete': 0},
    'records': {
        'order': [],
        'commplete': []
    }
})

statics().then((res: any) => {
    const { yesterday, week, month, records } = res.data
    state.yesterday = yesterday
    state.week = week
    state.month = month
    state.records = records
    setChart()
})

const countUpFun = (id: string) => {
    nextTick(() => {
        let value = document.getElementById(id)?.innerText
        if (value) {
            new CountUp(id, parseInt(value), {
                startVal: 0,
                duration: 3,
            }).start()
        }
    })
}

const initCountUp = () => {
    countUpFun('user_reg_number')
    countUpFun('file_number')
    countUpFun('users_number')
    countUpFun('addons_number')
}

const onChangeWorkState = () => {
    const time = parseInt((new Date().getTime() / 1000).toString())
    const workingTime = Local.get(WORKING_TIME)
    if (state.pauseWork) {
        // 继续工作
        workingTime.pauseTime += time - workingTime.startPauseTime
        workingTime.startPauseTime = 0
        Local.set(WORKING_TIME, workingTime)
        state.pauseWork = false
        startWork()
    } else {
        // 暂停工作
        workingTime.startPauseTime = time
        Local.set(WORKING_TIME, workingTime)
        clearInterval(workTimer)
        state.pauseWork = true
    }
}

const startWork = () => {
    const workingTime = Local.get(WORKING_TIME) || { date: '', startTime: 0, pauseTime: 0, startPauseTime: 0 }
    const currentDate = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
    const time = parseInt((new Date().getTime() / 1000).toString())

    if (workingTime.date != currentDate) {
        workingTime.date = currentDate
        workingTime.startTime = time
        workingTime.pauseTime = workingTime.startPauseTime = 0
        Local.set(WORKING_TIME, workingTime)
    }

    let startPauseTime = 0
    if (workingTime.startPauseTime <= 0) {
        state.pauseWork = false
        startPauseTime = 0
    } else {
        state.pauseWork = true
        startPauseTime = time - workingTime.startPauseTime // 已暂停时间
    }

    let workingSeconds = time - workingTime.startTime - workingTime.pauseTime - startPauseTime

    state.workingTimeFormat = formatSeconds(workingSeconds)
    if (!state.pauseWork) {
        workTimer = window.setInterval(() => {
            workingSeconds++
            state.workingTimeFormat = formatSeconds(workingSeconds)
        }, 1000)
    }
}

const formatSeconds = (seconds: number) => {
    var secondTime = 0 // 秒
    var minuteTime = 0 // 分
    var hourTime = 0 // 小时
    var dayTime = 0 // 天
    var result = ''

    if (seconds < 60) {
        secondTime = seconds
    } else {
        // 获取分钟，除以60取整数，得到整数分钟
        minuteTime = Math.floor(seconds / 60)
        // 获取秒数，秒数取佘，得到整数秒数
        secondTime = Math.floor(seconds % 60)
        // 如果分钟大于60，将分钟转换成小时
        if (minuteTime >= 60) {
            // 获取小时，获取分钟除以60，得到整数小时
            hourTime = Math.floor(minuteTime / 60)
            // 获取小时后取佘的分，获取分钟除以60取佘的分
            minuteTime = Math.floor(minuteTime % 60)
            if (hourTime >= 24) {
                // 获取天数， 获取小时除以24，得到整数天
                dayTime = Math.floor(hourTime / 24)
                // 获取小时后取余小时，获取分钟除以24取余的分；
                hourTime = Math.floor(hourTime % 24)
            }
        }
    }

    result =
        hourTime +
        t('dashboard.hour') +
        ((minuteTime >= 10 ? minuteTime : '0' + minuteTime) + t('dashboard.minute')) +
        ((secondTime >= 10 ? secondTime : '0' + secondTime) + t('dashboard.second'))
    if (dayTime > 0) {
        result = dayTime + t('dashboard.day') + result
    }
    return result
}

const setChart = ()=> {
    console.log('set')
        option = {
            title: {
                left: 'left',
                text: ''
            },
            xAxis: {
                type: 'category',
                data: []
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    data: [],
                    type: 'line'
                }
            ]
        };
        for (let index = 6; index >= 0; index--) {
            const date = new Date();
            const nowDay = date.getDate();
            date.setDate(nowDay - index);
            const str = timeFormat(Number(date), 'mm-dd')
            option.xAxis['data'].push(str)
        }
        option.title.text = "下单数量";
        console.log(option.xAxis['data'])
        option.xAxis['data'].forEach((date: any) => {
            const item = state.records.order.find((p: any) => p.day_full == date)
            if(item){
                option.series[0]['data'].push(item.count)
            } else {
                option.series[0]['data'].push(0)
            }
        })
        chart1.setOption(option);
        // option.series[0]['data'] = [46, 89, 104, 200, 289, 147, 160];
        option.title.text = "出货订单";
        option.series[0]['data'] = []
        option.xAxis['data'].forEach((date: any) => {
            const item = state.records.commplete.find((p: any) => p.day_full == date)
            if(item){
                option.series[0]['data'].push(item.count)
            } else {
                option.series[0]['data'].push(0)
            }
        })
        chart2.setOption(option);
    }

onActivated(() => {

})

onMounted(() => {
    startWork()
    initCountUp()
    chart1 = echarts.init(document.getElementById('chart1'));
    chart2 = echarts.init(document.getElementById('chart2'));
    // setChart();
})

onBeforeMount(() => {
    for (const key in state.charts) {
        state.charts[key].dispose()
    }
})

onUnmounted(() => {
    clearInterval(workTimer)
})

watch(
    () => navTabs.state.tabFullScreen,
    () => {
        
    }
)
</script>

<style scoped lang="scss">
.welcome {
    background: #e1eaf9;
    border-radius: 6px;
    display: flex;
    align-items: center;
    padding: 15px 20px !important;
    box-shadow: 0 0 30px 0 rgba(82, 63, 105, 0.05);
    .welcome-img {
        height: 100px;
        margin-right: 10px;
        user-select: none;
    }
    .welcome-title {
        font-size: 1.5rem;
        line-height: 30px;
        color: var(--ba-color-primary-light);
    }
    .welcome-note {
        padding-top: 6px;
        font-size: 15px;
        color: var(--el-text-color-primary);
    }
}
.working {
    height: 130px;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    height: 100%;
    position: relative;
    &:hover {
        .working-coffee {
            -webkit-transform: translateY(-4px) scale(1.02);
            -moz-transform: translateY(-4px) scale(1.02);
            -ms-transform: translateY(-4px) scale(1.02);
            -o-transform: translateY(-4px) scale(1.02);
            transform: translateY(-4px) scale(1.02);
            z-index: 999;
        }
    }
    .working-coffee {
        transition: all 0.3s ease;
        width: 80px;
    }
    .working-text {
        display: block;
        width: 100%;
        font-size: 15px;
        text-align: center;
        color: var(--el-text-color-primary);
    }
    .working-opt {
        position: absolute;
        top: -40px;
        right: 10px;
        background-color: rgba($color: #000000, $alpha: 0.3);
        padding: 10px 20px;
        border-radius: 20px;
        color: var(--ba-bg-color-overlay);
        transition: all 0.3s ease;
        cursor: pointer;
        opacity: 0;
        z-index: 999;
        &:active {
            background-color: rgba($color: #000000, $alpha: 0.6);
        }
    }
    &:hover {
        .working-opt {
            opacity: 1;
            top: 0;
        }
        .working-done {
            opacity: 1;
            top: 50px;
        }
    }
}
.row + .row { margin-top: 20px; }

.total-item {
    display: flex; justify-content: space-between; align-items: center; flex-flow: row;
    .text {
        .num { font-size: 24px;  }
        .info {}
    }
    > .icon {
        width: 50px; height: 50px; border-radius: 50px; display: flex; justify-content: center; align-items: center; background-color: #eee;
        .el-icon {
            font-size: 25px !important;
            color: inherit !important;
        }
    }
    .icon1 { color: var(--el-color-primary); background-color: var(--el-color-primary-light-9);}
    .icon2 { color: var(--el-color-success); background-color: var(--el-color-success-light-9);}
    .icon3 { color: var(--el-color-warning); background-color: var(--el-color-warning-light-9);}
    .icon4 { color: var(--el-color-danger); background-color: var(--el-color-danger-light-9);}
    .icon5 { color: var(--el-color-primary); background-color: var(--el-color-primary-light-9);}
    .icon6 { color: var(--el-color-success); background-color: var(--el-color-success-light-9);}
    .icon7 { color: var(--el-color-warning); background-color: var(--el-color-warning-light-9);}
    .icon8 { color: var(--el-color-danger); background-color: var(--el-color-danger-light-9);}
    .icon9 { color: var(--el-color-primary); background-color: var(--el-color-primary-light-9);}
    .icon10 { color: var(--el-color-primary); background-color: var(--el-color-primary-light-9);}
}

.chart { height: 400px; width: 100%;background-color: #ffffff;}
</style>
